#!/bin/bash
check_access() {
	if [ "$0" != "./dev-env.sh" ]; then
		echo -e "\e[31mERROR:安装失败，请进入到代码根目录运行\e[0m"
		echo -e "\e[31mERROR:安装失败，请进入到代码根目录运行\e[0m"
		echo -e "\e[31mERROR:安装失败，请进入到代码根目录运行\e[0m"
		exit -1
	fi
	if [[ $EUID -ne 0 ]]; then
		echo -e "\e[31mERROR:必须使用root运行\e[0m"
		exit -2
	fi
}

githook() {
	chmod +x tool/codeformat-githook.sh
	cp tool/codeformat-githook.sh ./.git/hooks/pre-commit
}

install() {
	# 编译
	apt-get install cmake

	# 代码规范化
	pip2 install yapf pytest pytest-mock pylint pytest-cov -i https://pypi.tuna.tsinghua.edu.cn/simple

	apt-get install clang-format-7
	apt-get install cppcheck
	if [ $(dpkg --print-architecture) == "amd64" ]; then
		cp tool/shfmt_v3.5.1_linux_$(dpkg --print-architecture) /usr/local/bin/shfmt
	fi
	cp tool/codeformat-githook.sh ./.git/hooks/pre-commit
	chown jakauser:jakauser ./.git/hooks/pre-commit
	chmod +x ./.git/hooks/pre-commit

	# 单元测试
	apt-get install lcov
	pip2 install pytest
	if [ ! -e "/usr/local/lib/libgtest.a" ]; then
		cd tool/googletest && mkdir -p build && cd build && cmake .. && make -j12 && make install
		rm -rf tool/googletest/build
	fi
}

sonarscanner() {
	tar xvf tool/sonar-scanner.tar.gz -C /opt
	echo "PATH=\$PATH:/opt/sonar-scanner/bin" >/etc/profile.d/jkzuc-build-env.sh
}

format_code() {
	find . -regextype posix-extended -regex ".*\.(c|cc|cpp|h|hh|hpp)" | xargs -i clang-format-7 -style=file -i {}
	find . -regextype posix-extended -regex ".*\.(sh|bash)" | xargs -i shfmt -w {}
}
main() {
	check_access
	sonarscanner
	install
	cp tool/build_env_version /usr/etc/build_env_version
	echo -e "\e[32m===成功安装jkzuc开发环境===\e[0m"
	echo -e "\e[32m===请重新执行autogen编译,若要使用sonar-scan进行代码检测请重启系统===\e[0m"
}

main
